import type { EventHandler, EventHandlerRequest } from 'h3';
import SessionModel from '~/models/SessionModel';

export default <T extends EventHandlerRequest, D>(handler: EventHandler<T, D>): EventHandler<T, D> =>
    defineEventHandler<T>(async event => {
        // auth payload
        const { _id: user_id } = event.context.auth;

        // session id
        const { session_id } = event.method === 'GET' ? getQuery(event) as any : await readBody(event);

        try {
            const session = await SessionModel.findById(session_id);
            if (session && session.user_id === user_id) {
                // record session
                event.context.session = session;
                const response = await handler(event)
                return response;
            }
        } catch (_) { }

        // invalid session
        throw createError({
            statusCode: 400,
            statusMessage: 'Invalid Session',
        });
    });